<?php

namespace Hansn\LaravelAddons\Providers;

use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;

class RouteServiceProvider extends ServiceProvider
{
    protected $modules;
    protected $namespace;

    public function boot()
    {
        if (file_exists(base_path(config('addons.path', 'addons') . DIRECTORY_SEPARATOR . 'addons.json'))) {
            $this->modules = get_object_vars(json_decode(file_get_contents(base_path(config('addons.path', 'addons') . DIRECTORY_SEPARATOR . 'addons.json'))));
        } else {
            $this->modules = [];
        }
        $this->namespace = config('addons.namespace', 'Addons');
        parent::boot();
    }

    public function map()
    {
        foreach ($this->modules as $k => $v) {
            if ($v == true && file_exists(base_path(config('addons.path', 'addons') . DIRECTORY_SEPARATOR . $k . DIRECTORY_SEPARATOR . "composer.json"))) {
                $this->mapApiRoutes($k);
                $this->mapWebRoutes($k);
                $this->mapView($k);
            }
        }

    }

    protected function mapWebRoutes($module)
    {
        Route::middleware('web')
            ->namespace($this->namespace."\${module}\Http\Controllers")
            ->group(base_path(config('addons.path', 'addons') . DIRECTORY_SEPARATOR .$module. DIRECTORY_SEPARATOR ."routes". DIRECTORY_SEPARATOR ."web.php"));
    }

    protected function mapApiRoutes($module)
    {
        Route::prefix('api')
            ->middleware('api')
            ->namespace($this->namespace."\${module}\Http\Controllers")
            ->group(base_path(config('addons.path', 'addons') . DIRECTORY_SEPARATOR .$module. DIRECTORY_SEPARATOR ."routes". DIRECTORY_SEPARATOR ."api.php"));
    }

    protected function mapView($module)
    {
        $this->loadViewsFrom(base_path(config('addons.path', 'addons') . DIRECTORY_SEPARATOR .$module. DIRECTORY_SEPARATOR."resources". DIRECTORY_SEPARATOR ."views"), Str::lower($module));
    }
}
